<template>
  <el-form class="login-form" status-icon :rules="loginRules" ref="loginForm" :model="loginForm" label-width="0">
    <el-form-item prop="userName">
      <el-input @keyup.enter="handleLogin" v-model="loginForm.userName" auto-complete="off"
        placeholder="请输入账号">
        <template #prefix>
          <i class="icon-yonghu"></i>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input @keyup.enter="handleLogin" type="password" show-password v-model="loginForm.password"
        auto-complete="off" :placeholder="$t('login.password')">
        <template #prefix>
          <i class="icon-mima"></i>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="code">
      <el-input @keyup.enter="handleLogin" :maxlength="code.len" v-model="loginForm.code" auto-complete="off"
        :placeholder="$t('login.code')">
        <template #prefix>
          <i class="icon-yanzhengma"></i>
        </template>
        <template #append>
          <div class="login-code">
            <img style="width: 100%;height: 100%;" :src="code.src" @click="refreshCode" />
          </div>
        </template>
      </el-input>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click.prevent="handleLogin" class="login-submit">{{ $t('login.submit') }}</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { mapGetters } from "vuex";
import { getCaptcha } from "@/api/login"
export default {
  name: "userlogin",
  data() {
    return {
      loginForm: {
        userName: "",
        password: "",
        code: "",
        captchaKey: "",
      },
      code: {
        src: "",
      },
      loginRules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 5, message: "密码长度最少为5位", trigger: "blur" }
        ],
        code: [
          { required: true, message: "请输入验证码", trigger: "blur" },
          { min: 4, max: 4, message: "验证码长度为4位", trigger: "blur" },
        ]
      }
    };
  },
  created() {
    this.refreshCode();
  },
  mounted() { },
  computed: {
    ...mapGetters(["tagWel"])
  },
  props: [],
  methods: {
    // 获取验证码
    refreshCode() {
      getCaptcha().then(res => {
        if (res.code == 200) {
          this.code.src = res.data.captchaImg;
          this.loginForm.captchaKey = res.data.captchaKey;
        }
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.$store.dispatch("LoginByUsername", this.loginForm).then(() => {
            this.$router.push(this.tagWel);
          });
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
:deep(.el-input-group__append) {
  padding: 0;
}

:deep(.el-input-group) {
  height: 42px;
}
</style>
